package com.example.nfcschool;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.example.nfcschool.MainActivity.SelectOneJsp;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TelChangeActivity extends Activity implements OnClickListener{

	EditText tel_et;
	EditText pw_et;
	TextView ch_tv;
	
	String telno="";
	String ttel="";
	String telCheck="";
	String snoCheck="";
	String sno ="";
	SmemberVO premem;
	int pw=0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tel_change);
		
		ActionBar actionBar = getActionBar();
        actionBar.hide();
		
		tel_et = (EditText)findViewById(R.id.tel_edit);
		pw_et = (EditText)findViewById(R.id.pw_edit);
		ch_tv = (TextView)findViewById(R.id.change_textbtn);
		
		ch_tv.setOnClickListener(this);
		
		Intent intent = getIntent();
		telno = intent.getStringExtra("tel");
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
	}
	
	
	@Override
	public void onClick(View v) {
		if(!pw_et.getText().toString().equals("")){
			ttel = tel_et.getText().toString();
			pw = Integer.parseInt(pw_et.getText().toString());
			new DuplicateJsp().execute();
	//		SDBHelper db = new SDBHelper(this, "1myDB", null, 1);
		}else{
			Toast.makeText(this, "데이터를 입력해주세요.", 2000).show();
			return;
		}
	}
	
	public void haha(){
		
		
		if(premem!= null){
			if(pw == premem.getPw()){
				new TelChangeJsp().execute();
				
//				if(db.telchange(ttel, telno)){
					Toast.makeText(this, "수정완료.다시 로그인해주세요.", Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
					startActivity(intent);
//				}
			}else{
				Toast.makeText(this, "암호를 확인해주세요.", Toast.LENGTH_SHORT).show();
			}
		}else{
			Toast.makeText(this, "존재하지 않는 연락처입니다.", Toast.LENGTH_SHORT).show();
		}
	}
	
	
	
	public class TelChangeJsp extends AsyncTask<Void, String, Void> {
		@Override
		protected Void doInBackground(Void... param) {
			try {
				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.10.67:8888/AndroidCheck/TelChange.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
				
				params.add(new BasicNameValuePair("oldtel", ttel));
				params.add(new BasicNameValuePair("newtel", telno));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();

				if (resEntity != null) {
					Log.i("RESPONSE", EntityUtils.toString(resEntity));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.e("TelChangeJsp?", "end?");
			
			Toast.makeText(TelChangeActivity.this, "수정완료.다시 로그인해주세요.", Toast.LENGTH_SHORT).show();
			Intent intent = new Intent(getApplicationContext(), MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			startActivity(intent);
			super.onPostExecute(result);
		}
	}
	
public class SelectOneJsp extends AsyncTask<Void, String, Void> {
		
		String tag="";
		StringBuilder sb=new StringBuilder();
	
		@Override
		protected Void doInBackground(Void... param) {
			
			try {
				try{
				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.10.67:8888/AndroidCheck/SelectOne.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
				
				params.add(new BasicNameValuePair("tel", ttel));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();
				
				if (resEntity != null) {
//						Log.i("RESPONSE", EntityUtils.toString(resEntity));
					sb.append(EntityUtils.toString(resEntity));
				}
				client.getConnectionManager().shutdown(); //추가된 코드.
				}catch(Exception ex){
					Log.i("preeeee",ex.toString());
					Log.i("tel",sb.toString());
				}
				
				
				
				// 데이터 받기
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
	    		factory.setNamespaceAware(true);             
	    		XmlPullParser xpp = factory.newPullParser(); 
	    		xpp.setInput(new StringReader(sb.toString()));   
	    		int eventType = xpp.getEventType();
	    		
	    		
	    		while(eventType != XmlPullParser.END_DOCUMENT){//현재 이벤트 타입이 END_DOCUMENT를 만날때 까지 반복.
	    			
		    		switch(eventType){
	    			case XmlPullParser.START_TAG :  // 이벤트 타입에 START_TAG 라면.
	    				tag = xpp.getName(); // 태그 이름을 추출함.
	    				if(tag.equals("smember")){
	    					premem = new SmemberVO();
	    				}else if(tag.equals("irum")) {
	    					premem.setIrum(xpp.nextText());
	    				}else if(tag.equals("tel")){
	    					premem.setTel(xpp.nextText());
	    				}else if(tag.equals("picture")){
	    					premem.setPicture(xpp.nextText());
	    				}else if(tag.equals("grade")){
	    					premem.setGrade(xpp.nextText());
	    				}else if(tag.equals("pw")){
	    					premem.setPw(1111);
	    				}else if(tag.equals("birth")){
	    					premem.setBirth(xpp.nextText());
	    				}else if(tag.equals("teach")){
	    					premem.setTeach(xpp.nextText());
	    				}else if(tag.equals("adds")){
	    					premem.setAdds(xpp.nextText());
	    				}else if(tag.equals("sno")){
	    					sno = xpp.nextText();
	    					premem.setSno(sno);
	    				}
	    			
	    				break;
	    			
	    			}
	    			eventType = xpp.next();
	    		}
				
				
			} catch (Exception e) {
				Log.e("SView Async Err",e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			
			Log.e("mainEnd?", "send?");
			if(premem!= null){
				haha();
				Log.d("SelectOne Success","premem is not null");
			}else{
				Log.d("SelectOne Fail","premem is NULL");
			}
			super.onPostExecute(result);
		}
	}
		
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	public class DuplicateJsp extends AsyncTask<Void, String, Void> {
		
		String tag="";
		StringBuilder sb=new StringBuilder();
	
		@Override
		protected Void doInBackground(Void... param) {
			
			try {
				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.10.67:8888/AndroidCheck/DuplicateCheck.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
				
				params.add(new BasicNameValuePair("tel",ttel));
				params.add(new BasicNameValuePair("sno", sno));
				
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();
				
				if (resEntity != null) {
					sb.append(EntityUtils.toString(resEntity));
				}
				client.getConnectionManager().shutdown(); //추가된 코드.
				
				
				// 데이터 받기
				XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
	    		factory.setNamespaceAware(true);             
	    		XmlPullParser xpp = factory.newPullParser(); 
	    		xpp.setInput(new StringReader(sb.toString()));   
	    		int eventType = xpp.getEventType();
	    		
	    		while(eventType != XmlPullParser.END_DOCUMENT){//현재 이벤트 타입이 END_DOCUMENT를 만날때 까지 반복.
	    			
		    		switch(eventType){
	    			case XmlPullParser.START_TAG :  // 이벤트 타입에 START_TAG 라면.
	    				tag = xpp.getName(); // 태그 이름을 추출함.
	    				if(tag.equals("tel")){
	    					telCheck = xpp.nextText();
	    				}else if(tag.equals("sno")){
	    					snoCheck = xpp.nextText();
	    				}
	    				break;
	    			
	    			}
	    			eventType = xpp.next();
	    		}
				
				
			} catch (Exception e) {
				Log.e("MainDuplicateCheck Async Err",e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			
			Log.e("mainDuplicateEnd?", "send?");
			
			if(telCheck.equals("true")) new SelectOneJsp().execute();
			
			super.onPostExecute(result);
		}
	}
	
	
	
}
